//
//  KLMPopupTableView.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/20.
//
import UIKit

// MARK: - 增强位置定义
enum PopupPosition {
    case automatic(anchorView: UIView, preferredDirection: Direction)
    case explicit(frame: CGRect, direction: Direction) // 包含方向参数
}

enum Direction {
    case up, down, left, right
}

// MARK: - 增强样式配置
struct PopupAppearance {
    var backgroundColor: UIColor = .white
    var maskViewColor: UIColor = .clear
    var cornerRadius: CGFloat = 8
    var shadowColor: UIColor = .lightGray
    var shadowOpacity: Float = 0.2
    var shadowRadius: CGFloat = 5
    var borderColor: UIColor = .lightGray
    var borderWidth: CGFloat = 0.5
    var cellHeight: CGFloat = 50
    var maxTableViewHeight: CGFloat = 300
    var popupWidth: CGFloat?
    var titleFont: UIFont = .systemFont(ofSize: 16)
    var subtitleFont: UIFont = .systemFont(ofSize: 12)
    var titleColor: UIColor = .black
    var subtitleColor: UIColor = .gray
    var leftIconWH: CGFloat = 50
    var rightIconWH: CGFloat = 24
    var animationType: AnimationType = .scale
}

enum AnimationType {
    case scale, slideFromTop, slideFromBottom, slideFromLeft, slideFromRight, fade
}

// MARK: - 增强数据模型
struct PopupItem {
    var title: String
    var subtitle: String?
    var leftIcon: String?  // 左侧图标
    var rightNormalIcon: String? // 右侧图标
    var rightSelectedIcon: String? // 右侧图标
    var selected: Bool
}

// MARK: - 协议
protocol PopupTableViewDelegate: AnyObject {
    func popupTableView(_ popupTableView: PopupTableView, didSelectRowAt indexPath: IndexPath)
    func popupTableViewDidDismiss(_ popupTableView: PopupTableView)
    func popupTableView(_ popupTableView: PopupTableView, didTapRightButtonAt indexPath: IndexPath)
    
    // 可选实现的头部相关方法
    func headerHeight(for popupTableView: PopupTableView) -> CGFloat
    func headerView(for popupTableView: PopupTableView) -> UIView?
    func headerTitle(for popupTableView: PopupTableView) -> String?
    func headerSubtitle(for popupTableView: PopupTableView) -> String?
    
    func footerHeight(for popupTableView: PopupTableView) -> CGFloat
    func footerView(for popupTableView: PopupTableView) -> UIView?
}

    // 提供默认实现
extension PopupTableViewDelegate {
    func popupTableView(_ popupTableView: PopupTableView, didSelectRowAt indexPath: IndexPath) {}
    func popupTableViewDidDismiss(_ popupTableView: PopupTableView) {}
    func popupTableView(_ popupTableView: PopupTableView, didTapRightButtonAt indexPath: IndexPath) {}
    
    func headerHeight(for popupTableView: PopupTableView) -> CGFloat { 0 }
    func headerView(for popupTableView: PopupTableView) -> UIView? { nil }
    func headerTitle(for popupTableView: PopupTableView) -> String? { nil }
    func headerSubtitle(for popupTableView: PopupTableView) -> String? { nil }
    
    func footerHeight(for popupTableView: PopupTableView) -> CGFloat { return 0 }
    func footerView(for popupTableView: PopupTableView) -> UIView? { return nil }
}

// MARK: - 主控件实现
class PopupTableView: UIView {
    
    // MARK: 公开属性
    weak var delegate: PopupTableViewDelegate?
    var items: [PopupItem] = []
    
    // MARK: 私有属性
    private let position: PopupPosition
    private let appearance: PopupAppearance
    private(set) var tableView: UITableView!
    private var backgroundMaskView: UIView!
    private var animationDuration: TimeInterval = 0.3
    private var currentDirection: Direction = .down
    
    // MARK: 初始化
    init(position: PopupPosition, appearance: PopupAppearance = PopupAppearance()) {
        self.position = position
        self.appearance = appearance
        super.init(frame: .zero)
        self.backgroundColor = appearance.backgroundColor
        configurePosition()
        setupUI()
    }
    
    required init?(coder: NSCoder) { fatalError() }
    
    // MARK: 公开方法
    func updateItems(_ items: [PopupItem]) {
        self.items = items
        reloadData()
    }
    
    func reloadData() {
        tableView.reloadData()
        calculateFrame()
    }
    
    func show() {
        guard let window = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window else {
            return
        }
        prepareForAnimation()
        window.addSubview(backgroundMaskView)
        backgroundMaskView.frame = window.bounds
        window.addSubview(self)
        // 配置头部视图
        if let header = createHeaderView() {
            tableView.tableHeaderView = header
        }
        if let footer = delegate?.footerView(for: self) {
            tableView.tableFooterView = footer
        }
        performEntranceAnimation()
    }
    
    @objc func dismiss() {
        performExitAnimation { [weak self] in
            self?.removeFromSuperview()
            self?.backgroundMaskView.removeFromSuperview()
            self?.delegate?.popupTableViewDidDismiss(self!)
        }
    }
    
    func setupWithDefaultItems(_ items: [PopupItem]) -> Void {
        self.items = items
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        adjustHeaderLayout()
    }
}

// MARK: - UI 配置
private extension PopupTableView {
    func configurePosition() {
        switch position {
        case .automatic(_, let direction):
            currentDirection = direction
        case .explicit(_, let direction):
            currentDirection = direction
        }
    }
    
    func setupUI() {
        setupMaskView()
        setupTableView()
        configureLayerStyle()
    }
    
    private func configureLayerStyle() { // 添加缺失的方法
        layer.shadowColor = appearance.shadowColor.cgColor
        layer.shadowOpacity = appearance.shadowOpacity
        layer.shadowRadius = appearance.shadowRadius
        layer.shadowOffset = CGSize(width: 0, height: 2)
        layer.cornerRadius = appearance.cornerRadius
        layer.borderColor = appearance.borderColor.cgColor
        layer.borderWidth = appearance.borderWidth
    }
    
    func setupMaskView() {
        backgroundMaskView = UIView()
        backgroundMaskView.backgroundColor = appearance.maskViewColor
        backgroundMaskView.alpha = 0
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismiss))
        backgroundMaskView.addGestureRecognizer(tapGesture)
    }
    
    func setupTableView() {
        tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(DefaultPopupCell.self, forCellReuseIdentifier: "DefaultCell")
        tableView.backgroundColor = .clear
        tableView.separatorInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        tableView.layer.cornerRadius = appearance.cornerRadius
        tableView.layer.borderColor = appearance.borderColor.cgColor
        tableView.layer.borderWidth = appearance.borderWidth
        tableView.tableFooterView = UIView()
        addSubview(tableView)
    }
    private func createHeaderView() -> UIView? {
        // 优先级1: 自定义视图
        if let customHeader = delegate?.headerView(for: self) {
            return configureCustomHeader(customHeader)
        }
        
        // 优先级2: 标题+副标题组合
        if let title = delegate?.headerTitle(for: self),
           let subtitle = delegate?.headerSubtitle(for: self) {
            return createDefaultHeader(title: title, subtitle: subtitle)
        }
        
        // 优先级3: 仅标题
        if let title = delegate?.headerTitle(for: self) {
            return createDefaultHeader(title: title, subtitle: nil)
        }
        
        // 优先级4: 仅副标题
        if let subtitle = delegate?.headerSubtitle(for: self) {
            return createDefaultHeader(title: nil, subtitle: subtitle)
        }
        
        return nil
    }
    
    private func configureCustomHeader(_ view: UIView) -> UIView {
        let container = UIView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: view.bounds.height))
        container.addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.snp.makeConstraints { make in
            make.edges.equalTo(container)
        }
        return container
    }
    
    private func createDefaultHeader(title: String?, subtitle: String?) -> UIView {
        let header = UIView()
        let titleLabel = UILabel()
        let subtitleLabel = UILabel()
        
        titleLabel.configStyle(font: UIFont(safeName: "PingFangSC-Medium", size: 14))
        subtitleLabel.configStyle(font: UIFont(safeName: "PingFangSC-Regular", size: 12))
        titleLabel.textAlignment = .center
        subtitleLabel.textAlignment = .center
        
        if let title = delegate?.headerTitle(for: self),
           let subtitle = delegate?.headerSubtitle(for: self) {
            header.addSubview(titleLabel)
            titleLabel.text = title
            titleLabel.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview().offset(8)
                make.bottom.equalTo(subtitleLabel.snp.top).offset(8)
            }
            header.addSubview(subtitleLabel)
            subtitleLabel.text = subtitle
            subtitleLabel.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
            }
        }
        if let title = delegate?.headerTitle(for: self) {
            titleLabel.text = title
            header.addSubview(titleLabel)
            titleLabel.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
        
        // 优先级4: 仅副标题
        if let subtitle = delegate?.headerSubtitle(for: self) {
            subtitleLabel.text = subtitle
            header.addSubview(subtitleLabel)
            subtitleLabel.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
        return header
    }
    
    private func adjustHeaderLayout() {
        guard let header = tableView.tableHeaderView else { return }
        
        let delegateHeight = delegate?.headerHeight(for: self)
        if delegateHeight != 0 {
            header.frame.size.height = delegateHeight!
        } else {
            // 自动布局更新
            let targetSize = CGSize(width: bounds.width, height: UIView.layoutFittingCompressedSize.height)
            let height = header.systemLayoutSizeFitting(targetSize).height
            if header.frame.height != height {
                header.frame.size.height = height
            }
        }
        tableView.tableHeaderView = header
        tableView.layoutIfNeeded()
    }
}

// MARK: - 布局计算
private extension PopupTableView {
    func calculateFrame() {
        switch position {
        case .automatic(let anchorView, _):
            calculateSmartPosition(anchorView: anchorView)
        case .explicit(let frame, _):
            self.frame = frame
        }
        tableView.frame = bounds
    }
    
    func calculateSmartPosition(anchorView: UIView) {
        guard let window = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window else {
            return
        }
        
        let anchorRect = anchorView.convert(anchorView.bounds, to: window)
        let screenSize = window.bounds.size
        var safeArea: UIEdgeInsets = .zero
        
        if #available(iOS 11.0, *) {
            safeArea = window.safeAreaInsets
        }
        
        // 动态计算逻辑（示例）
        let width = min(appearance.popupWidth ?? anchorRect.width, screenSize.width - 32)
        let height = min(CGFloat(items.count) * appearance.cellHeight, appearance.maxTableViewHeight)
        
        var origin = CGPoint.zero
        switch currentDirection {
        case .down:
            origin = CGPoint(x: anchorRect.midX - width/2, y: anchorRect.maxY + 8)
        case .up:
            origin = CGPoint(x: anchorRect.midX - width/2, y: anchorRect.minY - height - 8)
        case .left, .right:
            origin = anchorRect.origin
        }
        
        frame = CGRect(origin: origin, size: CGSize(width: width, height: height))
    }
}

// MARK: - 动画系统
private extension PopupTableView {
    func prepareForAnimation() {
        switch appearance.animationType {
        case .scale:
            transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
        case .slideFromTop:
            transform = CGAffineTransform(translationX: 0, y: -frame.maxY)
        case .slideFromBottom:
            transform = CGAffineTransform(translationX: 0, y: UIScreen.main.bounds.height - frame.minY)
        case .slideFromLeft:
            transform = CGAffineTransform(translationX: -frame.maxX, y: 0)
        case .slideFromRight:
            transform = CGAffineTransform(translationX: UIScreen.main.bounds.width - frame.minX, y: 0)
        case .fade:
            alpha = 0
        }
    }
    
    func performEntranceAnimation() {
        UIView.animate(withDuration: animationDuration) {
            self.transform = .identity
            self.alpha = 1
            self.backgroundMaskView.alpha = 1
        }
    }
    
    func performExitAnimation(completion: @escaping () -> Void) {
        UIView.animate(withDuration: animationDuration, animations: {
            self.prepareForAnimation()
            self.alpha = 0
            self.backgroundMaskView.alpha = 0
        }, completion: { _ in completion() })
    }
}

// MARK: - TableView 代理
extension PopupTableView: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DefaultCell", for: indexPath) as! DefaultPopupCell
        cell.configure(with: items[indexPath.row], appearance: appearance) {
            self.delegate?.popupTableView(self, didTapRightButtonAt: indexPath)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        delegate?.popupTableView(self, didSelectRowAt: indexPath)
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return appearance.cellHeight
    }
}

// MARK: - 增强默认单元格
class DefaultPopupCell: UITableViewCell {
    private let leftIconView = UIImageView()
    private let titleLabel = UILabel()
    private let subtitleLabel = UILabel()
    
    private var actionHandler: (() -> Void)?
    // 新增右侧按钮
    private let rightButton: UIButton = {
        let btn = UIButton(type: .custom)
        return btn
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    required init?(coder: NSCoder) { fatalError() }
    
    private func setupUI() {
        let textStack = UIStackView(arrangedSubviews: [titleLabel, subtitleLabel])
        textStack.axis = .vertical
        textStack.spacing = 4
        
        let mainStack = UIStackView(arrangedSubviews: [leftIconView, textStack, rightButton])
        mainStack.axis = .horizontal
        mainStack.spacing = 12
        mainStack.alignment = .center
        
        contentView.addSubview(mainStack)
        
        // 约束配置
        mainStack.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            mainStack.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
            mainStack.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -22),
            mainStack.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
            mainStack.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8)
        ])
        
        // 图标尺寸配置
        [leftIconView, rightButton].forEach {
            $0.contentMode = .scaleAspectFit
            $0.setContentHuggingPriority(.required, for: .horizontal)
            $0.setContentCompressionResistancePriority(.required, for: .horizontal)
        }
        
        NSLayoutConstraint.activate([
            leftIconView.widthAnchor.constraint(equalToConstant: 24),
            leftIconView.heightAnchor.constraint(equalTo: leftIconView.widthAnchor),
        ])
        rightButton.addTarget(self, action: #selector(tapRightBtn(_:)), for: .touchUpInside)
    }
    
    func configure(with item: PopupItem, appearance: PopupAppearance, actionHandler: @escaping () -> Void) {
        titleLabel.text = item.title
        titleLabel.font = appearance.titleFont
        titleLabel.textColor = appearance.titleColor
        
        subtitleLabel.text = item.subtitle
        subtitleLabel.font = appearance.subtitleFont
        subtitleLabel.textColor = appearance.subtitleColor
        subtitleLabel.isHidden = item.subtitle == nil
        
        if let leftIcon = item.leftIcon {
            leftIconView.image = UIImage(named: leftIcon)
        }
        leftIconView.isHidden = item.leftIcon == nil
        
        self.actionHandler = actionHandler
        
        rightButton.isHidden = item.rightNormalIcon == nil
        rightButton.setImage(UIImage(named: item.rightNormalIcon ?? "Role_no_select"), for: .normal)
        rightButton.setImage(UIImage(named: item.rightSelectedIcon ?? "Role_select"), for: .selected)
        rightButton.isSelected = item.selected
    }
    
    @objc private func tapRightBtn(_ btn: UIButton) {
        actionHandler?()
    }
}
